package com.example.front.controller;

import com.example.common.dto.JsonResult;
import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.front.dto.LevelCreateDto;
import com.example.front.dto.LevelDto;
import com.example.front.entity.Level;
import com.example.front.serivce.LevelService;
import com.example.interceptor.UserContext;
import com.example.passport.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@Api(tags = "严重等级")
@RestController
@CrossOrigin
@RequestMapping("/front/level")
public class LevelController {

    @Resource
    LevelService levelService;

    @ApiOperation("添加严重等级")
    @PostMapping("/create")
    public JsonResult<String> create(@Valid LevelCreateDto levelCreateDto) {
        if (levelCreateDto.getDuration() == 0) {
            return new JsonResult<>(false, "报警时间非法");
        }
        User user = UserContext.getUser();

        Level level = Level.builder().
                tenantId(user.getTenantId()).
                name(levelCreateDto.getName()).
                duration(levelCreateDto.getDuration()).build();

        levelService.createLevel(level);

        return new JsonResult<>(true, "添加成功");
    }

    @ApiOperation("获取严重等级列表")
    @GetMapping("/list")
    public JsonResult<ListDto<LevelDto>> list(Pagination pagination) {
        User user = UserContext.getUser();
        Level level = new Level();
        level.setTenantId(user.getTenantId());
        return new JsonResult<>(levelService.listLevel(level, pagination));
    }

    @ApiOperation("修改严重等级信息")
    @PostMapping("/update")
    public JsonResult<String> update(@Valid LevelDto levelDto) {
        if (levelDto.getDuration() == 0) {
            return new JsonResult<>(false, "报警时间非法");
        }
        User user = UserContext.getUser();

        levelService.updateLevel(user.getTenantId(), levelDto);

        return new JsonResult<>(true, "修改成功");
    }

    @ApiOperation("删除严重等级信息")
    @PostMapping("/delete")
    public JsonResult<String> deleteById(Long id) {
        User user = UserContext.getUser();
        levelService.deleteLevel(user.getTenantId(), id);
        return new JsonResult<>(true, "删除成功");
    }
}
